$(function () {
    $('button[title]').tooltip({container: 'body'});
    $('a[title]').tooltip({container: 'body'});

    //if (window.history && window.history.pushState) {
    //    $(window).on('popstate', function () {
    //        var hashLocation = location.hash;
    //        var hashSplit = hashLocation.split("#!/");
    //        var hashName = hashSplit[1];
    //        if (hashName !== '') {
    //            var hash = window.location.hash;
    //            if (hash === '') {
    //                window.location.href = "default.html"
    //            }
    //        }
    //    });
    //    window.history.pushState('forward', null, './#forward');
    //}
});

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
if (token == null || header == null) {
    alert("获取token失败");
}
else {
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
}

function logout() {
    $.post('$r.Logout', function () {
        window.location.href = "/";
    });
}

//alert字符串
var jMsgBox = "<div id='jMsgBox' class='alert alert-error'><button type='button' class='close' data-dismiss='alert'>×</button><h4 class='alert-heading'>错误！</h4><div>{0}</div></div>";
var jQueryMsgBox = "<div id='jQueryMsgBox' class='alert alert-error'><button type='button' class='close' data-dismiss='alert'>×</button><h4 class='alert-heading'>请确认您的操作！</h4><div>{0}</div><div><button class='btn btn-danger' type='button' style='margin-right:10px; margin-top:10px;'>确认</button><button class='btn btn-primary' type='button' style='margin-right:10px; margin-top:10px;'>取消</button></div></div>";

myResize(function () {
    var height = $("#divNavbarTop").height();
    $("body .container").css("padding-top", height + 20);
});

/**
 * 网页加载时和浏览器大小改变时触发
 * @param fn 当窗体发生改变时的回调
 */
function myResize(fn) {
    $(function () {
        fn();
        $(window).resize(fn);
    });
}

/**
 * 分页助手
 * @param form 分页关联的表单对象
 * @param pageIndex 第几页
 * @param type 上一页/下一页/跳转到某一页
 */
function pageHelper(form, pageIndex, type) {
    var pageTotal = parseInt(form.find("input[name='pageTotal']").val()) == "NaN" ? 1 : parseInt(form.find("input[name='pageTotal']").val());
    if (type == "prev") {
        pageIndex = pageIndex - 1;
    } else if (type == "next") {
        pageIndex = pageIndex + 1;
    }
    if (pageIndex <= 0 || parseInt(pageIndex) + "" == "NaN") pageIndex = 1;
    if (pageIndex > pageTotal) pageIndex = pageTotal;
    form.find("input[name='pageIndex']").val(pageIndex);
    form.submit();
}

/*在指定的时间后执行一段函数*/
function secs5Invoke(fn) {
    setTimeout(function () {
        if (fn != null) {
            fn();
        }
    }, 5000);
}
function secs10Invoke(fn) {
    setTimeout(function () {
        if (fn != null) {
            fn();
        }
    }, 1000 * 10);
}
function secsInvoke(fn, secs) {
    setTimeout(function () {
        if (fn != null) {
            fn();
        }
    }, secs * 1000);
}

/**
 * 重置表单
 * @param form 表单对象
 * @param btn 重置表单的按钮
 * @param valid 验证表单的对象
 */
function iReset(form, btn, valid) {
    if (valid != null) {
        valid.resetForm();
    }
    if (form != null) {
        form[0].reset();
        form.find("fieldset .control-group").each(function () {
            $(this).removeClass("error");
            $(this).find(".controls .help-inline").html("");
        });
    }
}

/**
 * 提交表单
 * @param form 表单对象
 * @param btn 提交表单的按钮
 * @param valid 验证表单的对象
 */
function iSubmit(form, btn, valid, success, fault, error) {
    //解决验证表单框架不能输入后再验证的问题 mydatatype = 'null'
    var inputs = form.find("input[mydatatype='null']");
    $(inputs).each(function () {
        if ($(this).val().trim() == 0) {
            valid.ignore($(this));
        }
        else {
            valid.unignore($(this));
        }
    });
    if (valid.check(false)) {
        var btnText = btn.html();
        $.ajax({
            type: "POST",
            url: form.attr("action"),
            data: form.serialize(),
            dataType: "json",
            success: function (msg) {
                if (msg.success) {
                    if (success != null) {
                        success(msg);
                    }
                    else {
                        window.location.href = form.attr("target");
                    }
                }
                else {
                    if (fault != null) {
                        fault(msg);
                    }
                    else {
                        insertMsgBox(form, msg.exception);
                    }
                }
            },
            error: function (data) {
                if (error != null) {
                    error(data);
                }
                else {
                    if (data.status == 200) {
                        window.location.href = form.attr("target");
                    } else if (data.status == 403) {
                        window.location.href = "/403.html";
                    }
                    else {
                        alert("i.js http-state:" + data.status + "&http-statusText:" + data.statusText);
                    }
                }
            },
            complete: function (msg) {
                btn.removeClass("disabled");
                btn.html(btnText);
                btn.removeAttr("disabled");
            }
        });
        btn.attr("disabled", "disabled");
        btn.addClass("disabled");
        btn.html("loading...");
    }
}

/**
 * ajaxPost请求 旧版本
 * @param url 请求的地址
 * @param data 请求的参数
 * @param sfn 请求成功时的回调
 * @param control 触发请求的按钮
 * @param html 请求失败时将错误显示到传入的html标签之前
 * @param ffn 请求失败时的回调
 */
function iAjaxPost(url, data, sfn, control, html, ffn) {
    var btnText = control.html();
    control.attr("disabled", "disabled");
    control.addClass("disabled");
    try {
        if (control.attr("type") == "button") {
            control.html("loading...");
        }
    } catch (e) {
    }
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function (msg) {
            if (msg.success) {
                if (sfn != null) {
                    sfn(msg);
                }
            }
            else {
                insertMsgBox(html, msg.exception);
                if (ffn != null) {
                    ffn(msg);
                }
            }
        },
        error: function (msg) {
            if (msg.status == 403) {
                window.location.href = "/403.html";
            } else {
                alert("yoms.js http-state: " + msg.status + " & http-statusText: " + msg.statusText);
            }
        },
        complete: function (msg) {
            control.removeClass("disabled");
            control.removeAttr("disabled");
            try {
                if (control.attr("type") == "button") {
                    control.html(btnText);
                }
            } catch (e) {
            }
        }
    });
}

/**
 * ajaxPost请求(2015-08-17)更新
 * @param url 请求的地址
 * @param data 请求的参数
 * @param sfn 请求成功时的回调
 * @param control 触发请求的按钮
 * @param html 请求失败时将错误显示到传入的指定标签之前
 * @param ffn 请求失败时的回调
 */
function yomsAjaxPost(url, data, control, htmllabel, sfn, ffn) {
    var btnText = control.html();
    control.attr("disabled", "disabled");
    control.addClass("disabled");
    try {
        if (control.attr("type") == "button") {
            control.html("loading...");
        }
    } catch (e) {
    }
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function (msg) {
            if (msg.success) {
                if (sfn != null) {
                    sfn(msg);
                }
            }
            else {
                insertMsgBox(htmllabel, msg.exception);
                if (ffn != null) {
                    ffn(msg);
                }
            }
        },
        error: function (msg) {
            if (msg.status == 403) {
                window.location.href = "/403.html";
            } else {
                alert("yoms.js http-state: " + msg.status + " & http-statusText: " + msg.statusText);
            }
        },
        complete: function (msg) {
            control.removeClass("disabled");
            control.removeAttr("disabled");
            try {
                if (control.attr("type") == "button") {
                    control.html(btnText);
                }
            } catch (e) {
            }
        }
    });
}

/**
 * 消息提示
 * @param html 将消息插入到html之前
 * @param msg 要显示的消息
 */
function insertMsgBox(html, msg) {
    if ($("#jMsgBox").length == 0) {
        html.before(String.format(jMsgBox, msg));
        $("#jMsgBox").hide();
        $("#jMsgBox").slideDown(200);
        secs10Invoke(function () {
            $("#jMsgBox").slideUp(200, function () {
                $(this).remove();
            });
        });
    }
    else {
        $("#jMsgBox div").html(msg);
    }
}

/**
 * 确认消息提示
 * @param html 将消息显示在html之前
 * @param msg 显示的消息
 * @param fn 用户已经确认时的回调
 * @param obj 确认回调需要传递的参数
 */
function insertMessageBox(html, msg, fn, obj) {
    if ($("#jQueryMsgBox").length == 0) {
        html.before(String.format(jQueryMsgBox, msg));
        $("#jQueryMsgBox").hide();
        $("#jQueryMsgBox").slideDown(200);
        secsInvoke(function () {
            $("#jQueryMsgBox").slideUp(200, function () {
                $(this).find("div:eq(0)").html("");
            });
        }, 30);
        $("#jQueryMsgBox button:eq(1)").bind("click", function () {
            if (fn != null) {
                fn(obj, html);
            }
            $("#jQueryMsgBox").slideUp(200, function () {
                $(this).find("div:eq(0)").html("");
            });
        });
        $("#jQueryMsgBox button:eq(2)").bind("click", function () {
            $("#jQueryMsgBox").slideUp(200, function () {
                $(this).find("div:eq(0)").html("");
            });
        });
    }
    else {
        $("#jQueryMsgBox").find("div:eq(0)").html(msg);
        $("#jQueryMsgBox").slideDown(300, function () {
        });
    }
}

/**
 * 根据文件显示图片
 * @param fileInfo
 * @returns {*}
 */
var readFileIntoDataUrl = function (fileInfo) {
    var loader = $.Deferred(),
        fReader = new FileReader();
    fReader.onload = function (e) {
        loader.resolve(e.target.result);
    };
    fReader.onerror = loader.reject;
    fReader.onprogress = loader.notify;
    fReader.readAsDataURL(fileInfo);
    return loader.promise();
};

/**
 * 将数组转换成json
 * @param o 数组
 * @returns {*} json字符串
 */
function arrayToJson(o) {
    var r = [];
    if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "object") {
        if (!o.sort) {
            for (var i in o)
                r.push(i + ":" + arrayToJson(o[i]));
            if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                r.push("toString:" + o.toString.toString());
            }
            r = "{" + r.join() + "}";
        } else {
            for (var i = 0; i < o.length; i++) {
                r.push(arrayToJson(o[i]));
            }
            r = "[" + r.join() + "]";
        }
        return r;
    }
    return o.toString();
}

(function ($) {
    /**
     * 格式化字符串
     * @returns {*}
     */
    String.format = function () {
        if (arguments.length == 0)
            return null;
        var str = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
            str = str.replace(re, arguments[i]);
        }
        return str;
    };

    /**
     * 激活表格单击选中行
     * @param on 当行被选中时触发回调
     * @param off 当行没有被选中触发回调
     * @param self 是否只允许选择一行数据
     */
    $.fn.activeTable = function (on, off, self) {
        /*设置行单击事件*/
        try {
            this.on("click", function (event) {
                if (self != null && self) {
                    $(this).parents("table").find(".warning").each(function (i) {
                        $(this).find("td input:checkbox").prop('checked', false);
                        $(this).removeClass('warning');
                    });
                }

                var result = $(this).find("td input:checkbox");
                if (!result.prop('checked')) {
                    $(this).find("td input:checkbox").prop("checked", true);
                    $(this).addClass('warning');
                }
                else {
                    $(this).find("td input:checkbox").prop('checked', false);
                    $(this).removeClass('warning');
                }

                if ($(this).parents("table").find(".warning").length > 0) {
                    if (on != null) {
                        on();
                    }
                } else {
                    if (off != null) {
                        off();
                    }
                }
            });
        } catch (e) {
            console.error('初始化表格行单击事件...' + e);
        }
    }

    /**
     * 验证表单
     */
    $.fn.myValid = function (efn, sfn) {
        var valid = this.Validform({
            showAllError: true,
            tiptype: function (msg, o, cssctl) {
                //alert(msg);
                //msg：提示信息;
                //o:{obj:*,type:*,curform:*}, obj指向的是当前验证的表单元素（或表单对象），type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
                //cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
                if (!o.obj.is("form")) {    //验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
                    var div = o.obj.parents("div .control-group");
                    var objtip = o.obj.siblings(".help-inline");
                    if (objtip[0] == null) {
                        objtip = div.find(".help-inline");
                    }
                    objtip.text(msg);
                    if (o.type != 3) {
                        objtip.text("");
//                        div.attr("class", "control-group");
                        div.attr("class", div.attr("validbak"));
                        if (sfn != null) {
                            sfn(o.obj);
                        }
                    }
                    else {
                        var isShowError = true;
                        //可为空但要检测数据格式的input
                        if (o.obj.attr("mydatatype") == "null") {
                            if (o.obj.val().trim().length == 0) {
                                objtip.text("");
                                isShowError = false;
                                div.removeClass("error");
                            }
                        }

                        if (isShowError) {
                            div.attr("validbak", div.attr("class"));
                            div.attr("class", "control-group error");
                        }

                        if (efn) {
                            efn(o.obj);
                        }
                    }
                }
            }
        });
        return valid;
    }

    /**
     * 填充表格中的空单元格
     */
    $.fn.fillEmptyCell = function () {
        try {
            this.each(function (i) {
                if ($(this).html().trim() == "") {
                    $(this).html("未填写");
                }
            });
        } catch (e) {
        }
    }

    /**
     * 设置单元格中的checkbox居中
     */
    $.fn.trCheckboxToCenter = function () {
        try {
            this.find("tr").css("background", "#F5F5F5");
            var headTd = this.find("tr").children("td:eq(0)");
            headTd.css("width", 30);
            headTd.css("text-align", "center");

            this.find("tbody > tr").each(function () {
                $(this).css("background", "white");

                var td = $(this).find("td:eq(0)");
                td.css("width", 30);
                td.css("text-align", "center");

                var checkbox = $(this).find('input:checkbox');
                if (checkbox.prop("checked" == null)) {
                    checkbox.prop("checked", false);
                }
                checkbox.attr('disabled', 'disabled');
            });
        } catch (e) {
            console.error('初始化表格checkbox居中异常...' + e);
        }
    }

    /**
     * 设置panel-body可打开关闭
     */
    $.fn.panelBodyToggle = function () {
        try {
            this.find(".panel-heading h3 a i").bind("click", function () {
                var i = $(this);
                $(this).parents(".panel").find('.panel-body').slideToggle("fast",
                    function () {
                        i.slideUp(100);
                        if (i.attr("class") == "icon-arrow-up") {
                            i.attr("class", "icon-arrow-down");
                        }
                        else {
                            i.attr("class", "icon-arrow-up");
                        }
                        i.slideDown(200);
                    });
            });
        } catch (e) {
            console.error('初始化动画异常...' + e);
        }
    }

    /**
     * 打开选择文件对话框
     * @param elm
     */
    $.fn.showFile = function () {
        var fileInput = this;
        fileInput.click();
        return this;
    }

    /**
     * 获取文件信息
     * @returns {*}
     */
    $.fn.getFileInfo = function () {
        var fileType = null;
        $.each(this[0].files, function (idx, fileInfo) {
            fileType = fileInfo;
        });
        return fileType;
    }

    /**
     * 显示错误
     * @param alerts 显示错误的容器
     * @param title 错误标题
     * @param msg 错误消息
     */
    $.fn.showError = function showError(title, msg) {
        $('<div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">&times;</button><strong>' + title + '</strong> ' + msg + ' </div>').prependTo(this);
        return this;
    };

    /**
     * 间隔30s请求一次服务器
     */
    $.ajax({
        url:"keepAlive.html",
        type:"post",
        dataType:"text",
        success: function (msg) {
            setInterval(function () {
                console.log(msg);
            }, 30 * 1000)
        },
        error: function () {
            console.log("保活失败");
        },
        complete: function () {

        }

    })
})(jQuery);